package com.imm.net.http.base

import android.annotation.SuppressLint
import java.io.DataOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
import java.security.cert.X509Certificate
import java.util.Scanner
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.X509TrustManager

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> HttpURLConnection 实现网络请求
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2024/7/22
 */
object BaseHttpUrlFactory {

    /**
     * 网络请求
     */
    fun openConnection(
        method: String,
        url: () -> URL? = { null },
        headers: () -> HashMap<String?, String?>? = { null },
        body: String? = null
    ): String?{
        val u = url()
        return createConnection(
            connection = addHeader(u, headers(), body)?.apply {
                requestMethod = method
                // 主要给低配（4.4以下）盒子用
                if ("https" == u?.protocol) {
                    val trustAllCert: X509TrustManager = @SuppressLint("CustomX509TrustManager")
                    object : X509TrustManager {
                        @SuppressLint("TrustAllX509TrustManager")
                        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {  }
                        @SuppressLint("TrustAllX509TrustManager")
                        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {  }
                        override fun getAcceptedIssuers(): Array<X509Certificate> {
                            return arrayOf()
                        }
                    }
                    (this as? HttpsURLConnection)?.sslSocketFactory = SSLSocketFactoryCompat(trustAllCert)
                }

                connectTimeout = 10000
                readTimeout = 10000
                doInput = true
                useCaches = false
            }
        )
    }

    /**
     * 请求添加head头
     */
    private fun addHeader(
        url: URL?,
        headerMap: HashMap<String?, String?>? = null,
        requestBody: String? = null
    ): HttpURLConnection? {
        val connection: HttpURLConnection = url?.openConnection() as? HttpURLConnection?: return null
        connection.setRequestProperty("Content-Type","application/json;charset=UTF-8")

        headerMap?.mapKeys {
            val key = it.key
            if (key?.isNotEmpty() == true){
                connection.setRequestProperty(key, it.value)
            }
        }

        // 添加 requestBody
        if (requestBody?.isNotEmpty() == true){
            connection.doOutput = true
            val input: ByteArray = requestBody.toByteArray(StandardCharsets.UTF_8)
            val out = DataOutputStream(connection.outputStream)
            out.write(input)
            out.close()
        }

        return connection
    }

    /**
     * 创建连接并解析输出流
     */
    private fun createConnection(
        connection: HttpURLConnection?
    ): String? {
        val responseCode = connection?.responseCode

        var result: String? = null
        if (responseCode == HttpURLConnection.HTTP_OK){
            val scanner = Scanner(connection.inputStream).useDelimiter("\\A")
            result = if (scanner.hasNext()) scanner.next() else ""
            scanner.close()
        }

        connection?.disconnect()
        return result
    }

}